from PyQt5.QtGui import QCursor
from PyQt5.QtCore import QStringListModel, Qt
from PyQt5.QtWidgets import QDialogButtonBox, QDialog, QLineEdit, QCompleter, QVBoxLayout, QListWidget

from libs.lib import newIcon, labelValidator

BB = QDialogButtonBox


class LabelDialog(QDialog):

    def __init__(self, text="Enter object label", parent=None, listItem=None):
        super(LabelDialog, self).__init__(parent)

        self.edit = QLineEdit()  # 单行文本框
        self.edit.setText(text)  # 文本内容
        self.edit.setValidator(labelValidator())  # 设置输入标准
        self.edit.editingFinished.connect(self.postProcess)  # 按下连接信号

        # 设置历史标签
        model = QStringListModel()
        model.setStringList(listItem)
        completer = QCompleter()  # 自动补全
        completer.setModel(model)
        self.edit.setCompleter(completer)

        layout = QVBoxLayout()  # 垂直布局
        layout.addWidget(self.edit)
        # 标签对话框按钮
        self.buttonBox = bb = BB(BB.Ok | BB.Cancel, Qt.Horizontal, self)
        bb.button(BB.Ok).setIcon(newIcon('done'))
        bb.button(BB.Ok).setShortcut("space")
        bb.button(BB.Cancel).setIcon(newIcon('undo'))
        bb.accepted.connect(self.validate)
        bb.rejected.connect(self.reject)
        layout.addWidget(bb)

        if listItem is not None and len(listItem) > 0:
            self.listWidget = QListWidget(self)
            for item in listItem:
                self.listWidget.addItem(item)
            self.listWidget.itemDoubleClicked.connect(self.listItemClick)
            layout.addWidget(self.listWidget)

        self.setLayout(layout)

    def validate(self):
        try:
            if self.edit.text().trimmed():
                self.accept()
        except AttributeError:
            # PyQt5: AttributeError: 'str' object has no attribute 'trimmed'
            if self.edit.text().strip():
                self.accept()

    def postProcess(self):
        try:
            self.edit.setText(self.edit.text().trimmed())
        except AttributeError:
            # PyQt5: AttributeError: 'str' object has no attribute 'trimmed'
            self.edit.setText(self.edit.text())

    def popUp(self, text='', move=True):
        """弹出窗口"""
        self.edit.setText(text)
        self.edit.setSelection(0, len(text))  # 获得显示的文本
        self.edit.setFocus(Qt.PopupFocusReason)  # 设置焦点，直接进入输入框
        if move:
            self.move(QCursor.pos())  # 跟着光标的位置移动
        return self.edit.text() if self.exec_() else None

    def listItemClick(self, tQListWidgetItem):
        """列表中点击"""
        try:
            text = tQListWidgetItem.text().trimmed()
        except AttributeError:
            # PyQt5: AttributeError: 'str' object has no attribute 'trimmed'
            text = tQListWidgetItem.text().strip()
        self.edit.setText(text)
        self.validate()
